#!/bin/bash
# 腾讯云服务器快速部署脚本 - CentOS/OpenCloudOS版本
# 使用方法：bash 快速部署脚本_CentOS.sh

set -e

echo "======================================"
echo "问卷系统自动部署脚本 (CentOS/OpenCloudOS)"
echo "======================================"
echo ""

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}请使用root权限运行此脚本${NC}"
    exit 1
fi

# 变量配置
PROJECT_NAME="审计"
PROJECT_DIR="/var/www/${PROJECT_NAME}"
VENV_DIR="${PROJECT_DIR}/backend/venv"
BACKEND_SERVICE="survey-backend"

# 获取服务器IP
SERVER_IP=$(curl -s ifconfig.me)
echo -e "${GREEN}检测到服务器IP: ${SERVER_IP}${NC}"
echo ""

# 1. 更新系统
echo "[1/9] 更新系统..."
yum update -y

# 2. 安装基础工具
echo "[2/9] 安装基础工具..."
yum install -y epel-release wget curl git gcc make openssl-devel bzip2-devel libffi-devel zlib-devel

# 3. 安装Python 3.11（从源码编译）
echo "[3/9] 安装Python 3.11..."
if ! command -v python3.11 &> /dev/null; then
    cd /tmp
    wget https://www.python.org/ftp/python/3.11.7/Python-3.11.7.tgz
    tar -xzf Python-3.11.7.tgz
    cd Python-3.11.7
    ./configure --enable-optimizations
    make altinstall
    ln -sf /usr/local/bin/python3.11 /usr/bin/python3.11
    ln -sf /usr/local/bin/pip3.11 /usr/bin/pip3.11
fi

# 4. 安装Node.js 18
echo "[4/9] 安装Node.js 18..."
if ! command -v node &> /dev/null; then
    curl -fsSL https://rpm.nodesource.com/setup_18.x | bash -
    yum install -y nodejs
fi

# 5. 安装Nginx
echo "[5/9] 安装Nginx..."
yum install -y nginx

# 6. 配置后端
echo "[6/9] 配置Django后端..."
cd ${PROJECT_DIR}/backend

# 创建虚拟环境
python3.11 -m venv venv
source venv/bin/activate

# 安装依赖
pip install --upgrade pip
pip install django djangorestframework django-cors-headers gunicorn python-dotenv

# 执行迁移
python manage.py migrate
python manage.py collectstatic --noinput

# 7. 配置Gunicorn服务
echo "[7/9] 配置Gunicorn服务..."
cat > /etc/systemd/system/${BACKEND_SERVICE}.service << EOF
[Unit]
Description=Survey Django Backend
After=network.target

[Service]
User=root
Group=root
WorkingDirectory=${PROJECT_DIR}/backend
Environment="PATH=${VENV_DIR}/bin"
ExecStart=${VENV_DIR}/bin/gunicorn \\
          --workers 3 \\
          --bind 127.0.0.1:8000 \\
          config.wsgi:application

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl start ${BACKEND_SERVICE}
systemctl enable ${BACKEND_SERVICE}

# 8. 构建前端
echo "[8/9] 构建前端..."
cd ${PROJECT_DIR}/frontend

# 修改API地址为相对路径
sed -i "s|const API_BASE_URL = .*|const API_BASE_URL = '/api'|g" src/api/survey.js

npm install
npm run build

# 9. 配置Nginx
echo "[9/9] 配置Nginx..."
cat > /etc/nginx/conf.d/survey.conf << EOF
server {
    listen 80;
    server_name ${SERVER_IP};

    location / {
        root ${PROJECT_DIR}/frontend/dist;
        try_files \$uri \$uri/ /index.html;
        index index.html;
    }

    location /api/ {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    location /static/ {
        alias ${PROJECT_DIR}/backend/staticfiles/;
    }
}
EOF

# 测试Nginx配置
nginx -t

# 启动Nginx
systemctl start nginx
systemctl enable nginx

# 配置防火墙
if command -v firewall-cmd &> /dev/null; then
    firewall-cmd --permanent --add-service=http
    firewall-cmd --permanent --add-service=https
    firewall-cmd --reload
fi

# 修改文件权限
chown -R root:root ${PROJECT_DIR}
chmod -R 755 ${PROJECT_DIR}

echo ""
echo "======================================"
echo -e "${GREEN}部署完成！${NC}"
echo "======================================"
echo ""
echo "访问地址: http://${SERVER_IP}"
echo ""
echo "常用命令:"
echo "  查看后端日志: journalctl -u ${BACKEND_SERVICE} -f"
echo "  重启后端: systemctl restart ${BACKEND_SERVICE}"
echo "  重启Nginx: systemctl restart nginx"
echo ""
echo "======================================"
